package com.leza.myapplication.ui.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.leza.myapplication.R;
import com.leza.myapplication.onenetapi.EntityData;
import com.leza.myapplication.onenetapi.HttpRequest;
import com.leza.myapplication.onenetapi.JsonAnalysis;
import com.leza.myapplication.ui.dashboard.DashboardFragment;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private XRecyclerView xr;
    private Handler mHandler;
    private List<EntityData> entityDataList;
    private final Handler tHandler = new Handler();
    private LinearAdapter linearAdapter;
    private ImageButton homeButton;
    private DashboardFragment webFragment;
    private Banner mBanner;
    private MyImageLoader mMyImageLoader;
    private ArrayList<Integer> imagePath;
    private ArrayList<String> imageTitle;

    private final Runnable tRunnable = new Runnable(){
        public void run(){
            getData();//更新数据
            System.out.println("我在计时！");
            tHandler.postDelayed(this,1000);//定时时间
        }
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        //初始化xr
        xr = root.findViewById(R.id.text_home);
        xr.setFocusableInTouchMode(false);

        //加布局管理器
        xr.setLayoutManager(new GridLayoutManager(getActivity(), 2));
//        xr.setLayoutManager(new LinearLayoutManager(getActivity()));
        entityDataList = new ArrayList<>();
        entityDataList.add(new EntityData(0.0f, "NULL"));
        linearAdapter = new LinearAdapter(getActivity(), entityDataList);
        xr.setAdapter(linearAdapter);

        initData();
        initView(root);

        getData();

        //允许刷新加载
        xr.setPullRefreshEnabled(true);
        xr.setLoadingListener(new XRecyclerView.LoadingListener() {
            //刷新
            @Override
            public void onRefresh() {
                getData();
                xr.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                xr.loadMoreComplete();
            }
        });

        homeButton = root.findViewById(R.id.home_button);
        homeButton.setOnClickListener(v -> {
            if (webFragment == null) {
                webFragment = new DashboardFragment();
            }
            requireActivity().getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, webFragment).commitAllowingStateLoss();
            TimerRefreshStop();
            System.out.println("正在切换到预览");
        });

        return root;
    }

    //初始化数据
    @SuppressLint("HandlerLeak")
    private void getData() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Bundle bundle = msg.getData();
                entityDataList = (List<EntityData>) bundle.getSerializable("entityDataList");

                if (entityDataList == null) {
                    entityDataList = new ArrayList<>();
                    entityDataList.add(new EntityData(0.0f, "NULL"));
                    return;
                }

                for (EntityData i : entityDataList) {
                    System.out.println(i);
                }

                linearAdapter.setEntityDataList(entityDataList);
                linearAdapter.notifyDataSetChanged();
            }
        };

        new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void run() {
                Message message = new Message();
                String url = "https://api.heclouds.com/devices/722044522/datapoints";
                // MQTT不需要token，MQTTS才需要
                String request =  HttpRequest.sendGet(url, "", "319981" , "E+eahjEL+uWbb1wy2IypL3HYSj2j18ApwlQtkXYMYW8=");
//                System.out.println(request + "in the Thread");
                message.what = 1;

                Bundle bundle = new Bundle();
                if (!"".equals(request)) {
                    bundle.putSerializable("entityDataList", (Serializable) JsonAnalysis.Analysis(request));
                } else {
                    System.out.println("连接失败了！" + request);
                }
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
        }).start();
    }

    public void TimerRefreshStart() {
        tHandler.removeCallbacks(tRunnable);
        tHandler.postDelayed(tRunnable,1000);
    }

    public void TimerRefreshStop() {
        tHandler.removeCallbacks(tRunnable);
    }

    private void initData() {
        imagePath = new ArrayList<>();
        imageTitle = new ArrayList<>();
        imagePath.add(R.mipmap.adv);
        imagePath.add(R.mipmap.adv_fun);
        imageTitle.add("PayPal广告");
        imageTitle.add("广告招商");
    }

    public void initView(View root) {

        mMyImageLoader = new MyImageLoader();
        mBanner = root.findViewById(R.id.banner_home);
        //设置图片加载器
        mBanner.setImageLoader(mMyImageLoader);
        //设置轮播的动画效果,里面有很多种特效,可以都看看效果。
        mBanner.setBannerAnimation(Transformer.ZoomOutSlide);
        //轮播图片的文字
        mBanner.setBannerTitles(imageTitle);
        //设置轮播间隔时间
        mBanner.setDelayTime(3000);
        //设置是否为自动轮播，默认是true
        mBanner.isAutoPlay(true);
        //设置图片加载地址
        mBanner.setImages(imagePath).start();
    }

    private static class MyImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context.getApplicationContext())
                    .load(path)
                    .into(imageView);
        }
    }
}